package com.raymond.entity.commons;

import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;

import javax.validation.constraints.Min;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

/**
 * desc-通用分页请求对象
 *
 * @author houmenghe
 * @date 2025/4/20 23:32
 **/
@Data
@NoArgsConstructor
@AllArgsConstructor
@Slf4j
public class PageRequest implements Serializable {

    private static final long serialVersionUID = -5767652223749064866L;

    /**
     * 分页默认大小
     */
    private static final Integer DEFAULT_PAGE_SIZE = 10;
    /**
     * 降序默认值
     */
    private static final Integer ORDER_DESC = 2;

    /**
     * 过滤sql中的特殊字符
     */
    private static final String REGEX = ".*([';]+|(--)+).*";

    /**
     * 第几页
     */
    @Min(value = 1, message = "分页页数必须大于等于1")
    private Integer pageNo = 1;
    /**
     * 每页大小
     */
    @Min(value = 0, message = "分页大小必须大于等于0")
    private Integer pageSize = DEFAULT_PAGE_SIZE;

    /**
     * 是否查询查询总条数
     */
    private boolean queryTotal = true;
    /**
     * 多排序
     */
    private List<SortBuilder> sorts;

    public Integer getPageStart() {
        if (null == pageNo) {
            pageNo = 1;
        }
        if (null == pageSize) {
            pageSize = DEFAULT_PAGE_SIZE;
        }
        return (pageNo - 1) * pageSize;
    }

    /**
     * 增加排序字段
     *
     * @param sortBuilder 排序字段、顺序
     * @return 当前实例
     */
    public PageRequest addSort(SortBuilder sortBuilder) {
        if (sorts == null) {
            sorts = new ArrayList<>();
        }
        sorts.add(sortBuilder);
        return this;
    }

    /**
     * 获取排序字段拼接字符串
     *
     * @return 排序字符串
     */
    public String getSortString() {
        if (sorts == null || sorts.size() == 0) {
            return null;
        }
        List<String> sortFields = new ArrayList<>();
        for (SortBuilder sortField : sorts) {
            String sortDirection = Objects.equals(1, sortField.getOrderBy()) ? "DESC" : "ASC";
            sortFields.add(String.format("%s %s", sortField.getSortField(), sortDirection));
        }
        return StringUtils.join(sortFields, ",");
    }
}
